package org.example.globalHandler;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.SourceLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 这个类用作于 service层次的使用记录
 * 什么意思呢？  我们想当用户调用请求执行service时记录一下 那个用户在什么时间段做了什么
 * 在service层次横切了整个业务  必须要修改原有的业务
 */
@Component
@Aspect
public class LoggerAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Pointcut(value = "execution(* org.example.service.imp.*.*(..))")
    public void pointCut(){

    }
    @Before(value = "pointCut()")
    public void before(JoinPoint joinpoint){
        //记录那个用户 在什么时间段 做了什么
        ServletRequestAttributes requestAttributes = null;
        try {
            requestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        }catch (Exception e){
            //可能表示在请求线程中吧 这个只有在请求线程中在可以获取  比如 kafka的consumer处理就是另外的请求
            return;
        }
        if (requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            String remoteHost = request.getRemoteHost();
            String currTime = simpleDateFormat.format(new Date());
            String name = joinpoint.getSignature().getName();
            String declaringTypeName = joinpoint.getSignature().getDeclaringTypeName();
            String methodName = declaringTypeName + "."+name;
            logger.info("用户"+remoteHost+"在"+currTime+",访问了"+methodName);
        }

    }



}
